package ua.com.jpy.entity.role;

import org.bson.types.ObjectId;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.security.core.GrantedAuthority;

import ua.com.jpy.entity.IEntity;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;

/**
 * @author LSD25
 *
 */
@Entity(noClassnameStored = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Role implements GrantedAuthority, IEntity {

	private static final long serialVersionUID = -5214603530670326252L;

	private static final String ROLE_ADMIN = "ROLE_ADMIN";
	
	private static final String ROLE_USER = "ROLE_USER";
	
	@Id
	private ObjectId id;

	@NotBlank
	private String role;

	private int roleInt;
	
	public ObjectId getId() {
		return id;
	}

	public void setId(ObjectId id) {
		this.id = id;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
		setRoleInt();
	}

	public int getRoleInt() {
		return roleInt;
	}

	private void setRoleInt() {
		if(role != null && !role.isEmpty()) {
			if(!role.equals(ROLE_ADMIN)) {
				this.roleInt = 0;
			} else {
				this.roleInt = 1;
			}
		}
	}

	@Override
	public String getAuthority() {
		if(this.roleInt == 0) {
			return ROLE_ADMIN;
		} else {
			return ROLE_USER;
		}
	}
	
}
